package com.solo.auth.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.solo.auth.service.LoginUserService;
import com.solo.common.core.utils.ServletUtils;
import com.solo.common.logger.event.LoginLogEvent;
import com.solo.satoken.model.LoginUser;
import com.solo.system.api.SysDeptApi;
import com.solo.system.api.SysRoleDeptApi;
import com.solo.system.api.consts.role.DataScope;
import com.solo.system.api.entity.SysLogLogin;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 登录用户服务实现类
 * @author 十一
 * @since 2024/11/29
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
public class LoginUserServiceImpl implements LoginUserService {

    @DubboReference
    private SysDeptApi sysDeptApi;
    @DubboReference
    private SysRoleDeptApi sysRoleDeptApi;
    
    @Override
    public void saveLoginLog(String username) {
        HttpServletRequest request = ServletUtils.getRequest();
        SysLogLogin loginLog = new SysLogLogin();
        loginLog.setUsername(username);
        loginLog.setIp(ServletUtils.getClientIP(request));
        // TODO 登录地址有问题
//        NetUtil.getDnsInfo()
//        loginLog.setLocation();
        String userAgent = ServletUtils.getUserAgent(request);
        loginLog.setUserAgent(userAgent);
        UserAgent ua = UserAgentUtil.parse(userAgent);
        loginLog.setDeviceName(ua.getPlatform().getName());
        loginLog.setBrowserName(ua.getBrowser().getName());
        SpringUtil.publishEvent(new LoginLogEvent(loginLog));
    }

    @Override
    public Set<Long> selectDataPermissions(LoginUser loginUser) {
        Set<DataScope> roleDataScopes = new HashSet<>();    // 数据范围集合
        Set<Long> customRoleIds = new HashSet<>();          // 自定义数据权限的角色id集合
        loginUser.getRoles().forEach(role -> {
            DataScope dataScope = role.getDataScope();
            roleDataScopes.add(dataScope);
            if (DataScope.CUSTOM.equals(dataScope)) {
                customRoleIds.add(role.getRoleId());
            }
        });
        
        //2.本部门数据权限
        Set<Long> dataPermissions = new HashSet<>();
        if (roleDataScopes.contains(DataScope.DEPT)) {
            dataPermissions.add(loginUser.getDeptId());
        }

        //3.本部门及以下数据权限
        if (roleDataScopes.contains(DataScope.DEPT_BELOW)) {
            Set<Long> deptIds = sysDeptApi.selectChildDeptIds(loginUser.getDeptId());
            dataPermissions.addAll(deptIds);
        }

        //4.查询自定义数据
        if (roleDataScopes.contains(DataScope.CUSTOM)) {
            List<Long> deptIds = sysRoleDeptApi.selectDeptIds(customRoleIds);
            dataPermissions.addAll(new HashSet<>(deptIds));
        }
        return dataPermissions;
    }

}
